package com.bootdo.output.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.bootdo.shop.domain.ShopDO;
import com.bootdo.shop.service.ShopService;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.bootdo.output.domain.ExcelResult;
import com.bootdo.output.domain.OutStorageDO;
import com.bootdo.output.domain.OutStorageDetailDO;
import com.bootdo.output.service.OutStorageDetailService;
import com.bootdo.output.service.OutStorageService;
import com.bootdo.output.utils.packageOutType;
import com.bootdo.provider.domain.ProviderInfoDO;
import com.bootdo.provider.service.ProviderInfoService;
import com.bootdo.put.domain.PutStorageDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.task.domain.TTaskDO;
import com.bootdo.task.domain.TTaskDatilDO;
import com.bootdo.task.service.TTaskDatilService;
import com.bootdo.task.service.TTaskService;
import com.bootdo.app.service.CreateTaskService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.goods.domain.TGoodsAllocationDO;
import com.bootdo.goods.service.TGoodsAllocationService;

/**
 * 出库订单表
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-04-26 16:50:51
 */

@Controller
@RequestMapping("/output/outStorage")
public class OutStorageController {
	@Autowired
	private OutStorageService outStorageService;
	@Autowired
	private  packageOutType packageOutType;
	@Autowired
	private com.bootdo.output.utils.analysisExcel analysisExcel;

	@Autowired
	private OutStorageDetailService outStorageDetailService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private CreateTaskService createTaskService;
	@Autowired
	private  ProviderInfoService providerInfoService;
	@GetMapping()
//	@RequiresPermissions("output:outStorage:outStorage")
	String OutStorage() {
		return "output/outStorage/outStorage";
	}

	@ResponseBody
	@GetMapping("/list")
//	@RequiresPermissions("output:outStorage:outStorage")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		UserDO  do1 = 	ShiroUtils.getUser();
		if(do1.getProviderId()!= null) {
			params.put("providerId", do1.getProviderId());
			params.put("outstorageStatus", "12201");
		}
		Query query = new Query(params);
		List<OutStorageDO> outStorageList = outStorageService.list(query);
		for (OutStorageDO outStorageDO : outStorageList) {
			outStorageDO = packageOutType.packageOutStoragePojo(outStorageDO);
		}
		int total = outStorageService.count(query);
		PageUtils pageUtils = new PageUtils(outStorageList, total);
		return pageUtils;
	}
 

	@GetMapping("/add")
	String add() {
		return "output/outStorage/addOrder";
	}

	@GetMapping("/edit/{outstorageId}")
//	@RequiresPermissions("output:outStorage:edit")
	String edit(@PathVariable("outstorageId") Long outstorageId, Model model) {
		OutStorageDO outStorage = outStorageService.get(outstorageId);
		model.addAttribute("outStorage", outStorage);
		return "output/outStorage/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save(OutStorageDO outStorage) {
		if (outStorageService.save(outStorage) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update(OutStorageDO outStorage) {
		outStorageService.update(outStorage);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	public R remove(Long outstorageId) {
		if (outStorageService.remove(outstorageId) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Long[] outstorageIds) {
		outStorageService.batchRemove(outstorageIds);
		return R.ok();
		
	}
	
	/**
	 * 下单
	 */
	@PostMapping("/batchUpdate")
	@ResponseBody
	public R update(@RequestParam("ids[]") Long[] outstorageIds) {
		outStorageService.batchUpdate(outstorageIds);
		UserDO  user = ShiroUtils.getUser();
		createTaskService.createTasks(user.getProviderId());
		return R.ok();
	}

	@ResponseBody
	@RequestMapping("/getOutStorageDO")
	public OutStorageDO getgetOutStorageDO(HttpSession session) {
		UserDO userDO = ShiroUtils.getUser();
		Long s = (Long) session.getAttribute("outId");
		if (s!= -userDO.getProviderId()){
			OutStorageDO outStorageDO = outStorageService.get(s);
			outStorageDO= packageOutType.packageOutStoragePojo(outStorageDO);
			return outStorageDO;
		}
		return  null;

	}

	/**
	 * 查看有无session
	 * @param session
	 * @return
	 */
	@GetMapping("/getsession")
	@ResponseBody
	private String getSession(HttpSession session) {
		String message = (String) session.getAttribute("UploadTheAbnormal");
		session.removeAttribute("UploadTheAbnormal");
		return message;
	}

	/**
	 * 用户生成订单
	 * @param shopName
	 * @param outstorageOrderid
	 * @param session
	 * @return
	 */
	@PostMapping("/saveOrder")
	@ResponseBody
	public R saveOrder(String shopName ,Long outstorageOrderid,String oddNumbers,String linkmane,String phone,String address,HttpSession session){
		UserDO userDO = ShiroUtils.getUser();
		Long s = (Long) session.getAttribute("outId");
		Map<String,Object> shopMap = new HashMap<>();
		shopMap.put("providerId",userDO.getProviderId());
		shopMap.put("shopName",shopName);
		List<ShopDO> shopDOS = shopService.list(shopMap);
		ShopDO shopDO = null;
		if(shopDOS.size()>0){
			 shopDO = shopDOS.get(0);
		}else{
			return  R.error("系统错误");
		}
		Integer sum = 0;
		Double sumPrice = 0.0;
		OutStorageDO do1 = new OutStorageDO();

		do1.setAddress(address);//地址
		do1.setOddNumbers(oddNumbers);//单号
		do1.setLinkman(linkmane);//联系人
		do1.setPhone(phone);//电话
		do1.setOutstorageOrderid(outstorageOrderid);//加急状态
		if(s==-userDO.getProviderId()){
			do1.setProviderId(userDO.getProviderId());// 供应商id；
			do1.setOutstorageDate(new Date());
			do1.setOutstorageShopid(shopDO.getShopId().toString());
			do1.setOutstorageStatus("12201");//未发布
			outStorageService.save(do1);
			Map<String,Object> Map = new HashMap<>();
			Map.put("outId",s);
			List<OutStorageDetailDO> outStorageDetailDOS = outStorageDetailService.list(Map);
			OutStorageDetailDO d = null;
			for ( OutStorageDetailDO outStorageDetailDO: outStorageDetailDOS) {
				d =new OutStorageDetailDO();
				sum +=	outStorageDetailDO.getDatilAmount();
				sumPrice += new Double(	outStorageDetailDO.getTotalPrices());
				d.setDatilId(outStorageDetailDO.getDatilId());
				d.setOutId(do1.getOutstorageId());
				outStorageDetailService.update(d);
			}
			OutStorageDO do2 = new OutStorageDO();
			do2.setOutstorageId(do1.getOutstorageId());
			do2.setTotalMoney(sumPrice.toString());//总价
			do2.setTotalQuantity(sum.toString());//总数
			outStorageService.update(do2);
		}else{
			do1.setOutstorageId(s);
			Map<String,Object> Map = new HashMap<>();
			Map.put("outId",s);
			List<OutStorageDetailDO> outStorageDetailDOS = outStorageDetailService.list(Map);
			for ( OutStorageDetailDO outStorageDetailDO: outStorageDetailDOS) {
				sum +=	outStorageDetailDO.getDatilAmount();
				sumPrice += new Double(	outStorageDetailDO.getTotalPrices());
			}
			do1.setTotalMoney(sumPrice.toString());//总价
			do1.setTotalQuantity(sum.toString());//总数
			outStorageService.update(do1);
		}
		return R.ok();
	}

	/**
	 * 判断用户输入门店是否正确
	 * @param shopName
	 * @return
	 */
	@GetMapping("/shopNameISExist")
	@ResponseBody
	public  Boolean shopNameISExist(String shopName){
		UserDO userDO = ShiroUtils.getUser();

		List<ShopDO> strings = shopService.getShop(shopName, userDO.getProviderId());
		if(strings.size()>0)
			return true;
		return false;
	}
	/**
	 * 上传商品
	 * @param files
	 * @param session
	 * @return
	 */
	@PostMapping("/multifileUpload")
	public  String multifileUpload(@RequestParam("fileName") List<MultipartFile> files,HttpSession session) {
		String msg=""; 
		Date date = new Date(); 
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); 
		SimpleDateFormat s = new SimpleDateFormat("YYYY-MM-dd"); 
		msg+=sdf.format(date); 
		  UserDO  user = ShiroUtils.getUser();
		  Integer count = 1;
		  for (MultipartFile multipartFile : files) {
			InputStream file;
			try {
				file = multipartFile.getInputStream();
				String fileName = multipartFile.getOriginalFilename();
				int fileSize  = (int) multipartFile.getSize();
				ExcelResult excelResult =	analysisExcel.excel(fileName,file,user.getProviderId());
				if(excelResult.getOutStorageDO()==null) {
					//session.setAttribute("UploadTheAbnormal", "上传异常");
					if(excelResult.getShopName()!=null)
						session.setAttribute("UploadTheAbnormal", "上传订单表格第"+count+"个文件中 门店："+excelResult.getShopName()+"不存在");
					if(excelResult.getGoodName()!=null && excelResult.getMessage() == null)
						session.setAttribute("UploadTheAbnormal", "上传订单表格第"+count+"个文件中 商品："+excelResult.getGoodName()+"不存在");
					if(excelResult.getGoodName()!=null && excelResult.getMessage() != null)
						session.setAttribute("UploadTheAbnormal", "上传订单表格第"+count+"个文件中 商品："+excelResult.getGoodName()+"库存不足");
					
					return "output/outStorage/outStorage";
				}
				String excel = fileName.substring(fileName.indexOf("."));
				//获取供应商名称
				ProviderInfoDO provider = 	providerInfoService.get(user.getProviderId());
				File f = new File("");
				Date d = new Date(); 
				String path =f.getAbsolutePath().toString()+"//files//"+provider.getProviderFname()+"//"+s.format(d);
				String newName= msg+"-"+fileName;
				f = new File(path);
				FileOutputStream fos = null;
				if (!f.exists())  
					f.mkdirs();  
				if (!multipartFile.isEmpty()) { 
					f = new File(path+"//"+newName);
					multipartFile.transferTo(f);
					file.close(); 
				}  
			} catch (IOException e) {
				e.printStackTrace();
			}
			count ++;
		}
		   return "output/outStorage/outStorage";
	}
	
	/*wlst订单出库界面*/
	
	@GetMapping("wlst")
//	@RequiresPermissions("output:outStorage:wlst:outStorage")
	String OutStorageWlst() {
		return "output/outStorage/wlst/outStorage";
	}
	
	@ResponseBody
	@GetMapping("/list/wlst")
//	@RequiresPermissions("output:outStorage:wlst:outStorage")
	public PageUtils listWlst(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OutStorageDO> outStorageList = outStorageService.list(query);
		int total = outStorageService.count(query);
		PageUtils pageUtils = new PageUtils(outStorageList, total);
		return pageUtils;
	}
	
	/* my 供应商*/
	@GetMapping("my")
	String OutStorageMy() {
		return "output/outStorage/my/outStorage";
	}
	
	@ResponseBody
	@GetMapping("/list/my")
	public PageUtils listWlstMy(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OutStorageDO> outStorageList = outStorageService.list(query);
		int total = outStorageService.count(query);
		PageUtils pageUtils = new PageUtils(outStorageList, total);
		return pageUtils;
	}
	
	/*根据状态查询*/	
	@ResponseBody
	@GetMapping("/status")
	public List<OutStorageDO> listStatus() {
		return outStorageService.listStatus();
	};
	
	@ResponseBody
	@GetMapping("/list/{status}")
	public List<OutStorageDO> listByType(@PathVariable("status") String status) {
		// 查询列表数据
		Map<String, Object> map = new HashMap<>();
		map.put("status", status);
		List<OutStorageDO> statusList = outStorageService.list(map);
		return statusList;
	}
	
}
